import json
from datetime import datetime
import requests
import time


def download_video(url, headers, file_path):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            with open(file_path, mode='wb') as f:
                f.write(response.content)
            return True
        else:
            print(f"下载失败，状态码: {response.status_code}")
    except Exception as e:
        print(f"下载时出现错误: {e}")
    return False


def save_info(data, info_file_path):
    try:
        json_data = json.dumps(data, ensure_ascii=False)
        with open(info_file_path, 'a', encoding='utf-8') as f:
            f.write(json_data)
            f.write('\n')
        print(json_data)
    except Exception as e:
        print(f"保存信息时出现错误: {e}")


downloaded_count = 0
for b in range(1000):  # 假设足够多的页面
    if downloaded_count >= 5000:
        break

    cookies = {
        'kpf': 'PC_WEB',
        'clientid': '3',
        'did': 'web_0983c4cf73244c992ad03fcd5470228c',
        'userId': '4662483062',
        'kuaishou.server.webday7_st': 'ChprdWFpc2hvdS5zZXJ2ZXIud2ViZGF5Ny5zdBKwAbYhF9V_SKtF9VFulQnhYrGRv1k8VM0r3BLAMgZVKJdAOPs8JAbkyHznsrBY27sY1avQs9pOwCh7-OtWwSHBOksxLvisIkec4ERXLvF0QNaWwv5iZMaOXbB5-TWRydSrn5rl2orWGG54bmoK0npihGGh6uQDRx4ydeT3khsdgZbDZqrS08wsZhzQM1-jglWVmAhhQf8AxqPo6-WjUZVbv8cLIQRkGeL_uCyC8iuYKEvIGhIA_XdAncGwkwk-cQy5RQPEn5UiICx9jXX62tQeT3S9koQkXgNr8BY7EY4m0gj1Gn0Bs9R8KAUwAQ',
        'kuaishou.server.webday7_ph': '60e05192b9016e37094f0db9af7d7a05a66a',
        'ktrace-context': '1|MS43NjQ1ODM2OTgyODY2OTgyLjgzNzE4MTU0LjE3NDExNjA4NjAyNjcuMzA0NDc2|MS43NjQ1ODM2OTgyODY2OTgyLjIzNzkyNzg1LjE3NDExNjA4NjAyNjcuMzA0NDc3|0|graphql-server|webservice|false|NA',
        'kpn': 'KUAISHOU_VISION',
    }

    headers = {
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Origin': 'https://www.kuaishou.com',
        'Pragma': 'no-cache',
        'Referer': 'https://www.kuaishou.com/short-video/3xu3wsj3n3iuw5a?authorId=3xarzg456cbugx9&streamSource=search&area=searchxxnull&searchKey=%E6%96%B0%E7%96%86%E5%93%88%E5%AF%86%E5%B8%82%E6%99%AE%E9%80%9A%E8%AF%9D',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0',
        'accept': '*/*',
        'content-type': 'application/json',
        'sec-ch-ua': '"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    json_data = {
        'operationName': 'visionSearchPhoto',
        'variables': {
            'keyword': '新疆普通话剧',
            'pcursor': str(b),
            'page': 'search',
            'searchSessionId': 'MTRfNDY2MjQ4MzA2Ml8xNzQxMTY2NTg2MDY3X-mHjeW6huivnV8xMjE3',
        },
        'query': 'fragment photoContent on PhotoEntity {\n  __typename\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  commentCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {\n    url\n    __typename\n  }\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  riskTagContent\n  riskTagUrl\n}\n\nfragment recoPhotoFragment on recoPhotoEntity {\n  __typename\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  commentCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {\n    url\n    __typename\n  }\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  riskTagContent\n  riskTagUrl\n}\n\nfragment feedContent on Feed {\n  type\n  author {\n    id\n    name\n    headerUrl\n    following\n    headerUrls {\n      url\n      __typename\n    }\n    __typename\n  }\n  photo {\n    ...photoContent\n    ...recoPhotoFragment\n    __typename\n  }\n  canAddComment\n  llsid\n  status\n  currentPcursor\n  tags {\n    type\n    name\n    __typename\n  }\n  __typename\n}\n\nquery visionSearchPhoto($keyword: String, $pcursor: String, $searchSessionId: String, $page: String, $webPageArea: String) {\n  visionSearchPhoto(keyword: $keyword, pcursor: $pcursor, searchSessionId: $searchSessionId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      ...feedContent\n      __typename\n    }\n    searchSessionId\n    pcursor\n    aladdinBanner {\n      imgUrl\n      link\n      __typename\n    }\n    __typename\n  }\n}\n',
    }

    try:
        response = requests.post('https://www.kuaishou.com/graphql', cookies=cookies, headers=headers, json=json_data)
        response.raise_for_status()
        response_text = response.json()
        now = datetime.now()

        for i in range(len(response_text.get('data', {}).get('visionSearchPhoto', {}).get('feeds', []))):
            if downloaded_count >= 5000:
                break
            try:
                time.sleep(2)
                downloaded_count += 1
                url_1 = response_text['data']['visionSearchPhoto']['feeds'][i]['photo']['manifest']['adaptationSet'][0][
                    'representation'][0]['url']
                data_1 = {"province": "新疆省", "city": "哈密市", "website": "快手",
                          "persons": {"crawl_person": "张亮"},
                          "times": {"crawl_time": str(now)}, "file": {"duration": "10",
                                                                      "local_filename": r"f:\xinjiang-origin4\6505_250320_00000{}_origin.wav".format(
                                                                          downloaded_count)}}
                if download_video(url_1, headers,
                                  r"D:\Users\Hasee\Desktop\工作\新疆\xinjiang-origin4\6505_250320_00000{}_origin.wav".format(
                                          downloaded_count)):
                    print('下载完成{}'.format(downloaded_count))
                    save_info(data_1, r'D:\Users\Hasee\Desktop\工作\新疆\xinjiang-origin4\数据记录.txt')
            except KeyError as e:
                print(f"解析数据时出现 KeyError: {e}")
            except Exception as e:
                print(f"处理视频时出现错误: {e}")
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except ValueError as e:
        print(f"解析 JSON 时出错: {e}")


